<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Validate;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;

    }


    /**
     * 列表
     *
     */
    public function list()
    {
        $name = $this->request->post("name/s");
        $page = $this->request->post("page/d",1);
        $pageSize = $this->request->post("pageSize/d",10);
        $status = $this->request->post("status/d");
        $sort = $this->request->post("sort/s",'createtime');
        $order = $this->request->post("order/s",'desc');
        $where = [];
        $name && $where['goods.name'] = ['like','%'.$name.'%'];
        $status && $where['order.status'] = $status;
        $total = $this->model
            ->with('goods,user,distributor,verifier')
            ->where($where)
            ->count();
        $totalPages = max(ceil($total / $pageSize),1);
        $page = max(min($page, $totalPages),1);
        $list = $this->model
            ->with('goods,user,distributor,verifier')
            ->where($where)
            ->order($sort, $order)
            ->page($page, $pageSize)
            ->select();
        $this->success('返回成功', [
            'list'       => $list,
            'total'      => $total,
            'page'       => $page,
            'pageSize'   => $pageSize,
            'totalPages' => $totalPages,
        ]);
    }


    /**
     * 详情
     *
     */
    public function detail()
    {
        $id = $this->request->post("id");
        $goods = $this->model
            ->with('goods,user,distributor,verifier')
            ->where([
                'order.id' => $id,
                'order.user_id|order.distributor_id|order.verifier_id' => $this->auth->id,
            ])
            ->find();
        $this->success('返回成功', $goods);
    }


    /**
     * 新增
     *
     */
    public function add()
    {
        $data = [
            'goods_id'        => $this->request->post('goods_id/s'),
            'coupon_id'       => $this->request->post('coupon_id/s') ?: null,
            'user_id'         => $this->auth->id,
            'distributor_id'  => $this->request->post('distributor_id/s') ?: null,
            'status'          => 1,
            'travel_date'     => $this->request->post('travel_date/s'),
            'tourists'        => $this->request->post('tourists/s'),
            'contacts_name'   => $this->request->post('contacts_name/s') ?: $this->auth->nickname,
            'contacts_mobile' => $this->request->post('contacts_mobile/s') ?: $this->auth->mobile,
            'contacts_area'   => $this->request->post('contacts_area/s'),
            'remarks'         => $this->request->post('remarks/s'),
            'review_status'   => 0,
        ];
        $rule = [
            'goods_id'        => 'require|number',
            'travel_date'     => 'require|date',
            'tourists'        => 'require',
            'contacts_mobile' => 'require|mobile',
        ];
        $msg = [
            'goods_id.require'       => '请选择商品',
            'tourists.require'       => '至少需要一位游客',
            'contacts_mobile.mobile' => '手机号格式错误',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $goods = db('goods')
            ->where([
                'id' => $data['goods_id'],
                'inventory' => ['>=',1],
                'status'    => 3,
            ])
            ->find();
        !$goods && $this->error('商品无效');
        $data['goods_price'] = $goods['price'];
        $data['return_date'] = date('Ymd', strtotime($data['travel_date'] . ' +1 day'));
        if ($data['distributor_id']) {
            $distributor = db('user')
                ->where([
                    'id'       => $data['distributor_id'],
                    'group_id' => 2,
                    'status'   => 'normal',
                ])
                ->find();
            !$distributor && $this->error('分销员无效');
        }
        $tourists_ids = explode(",",$data['tourists']);
        $tourists = db('User_tourists')
            ->where([
                'id'      => ['in',$tourists_ids],
                'user_id' => $this->auth->id,
            ])
            ->field('name,type,id_num')
            ->select();
        !$tourists && count($tourists_ids) != count($tourists) && $this->error('游客信息无效');
        $data['tourists'] = json_encode($tourists);
        $data['tourists_num'] = count($tourists_ids);
        $order = $this->model
            ->where([
                'user_id'    => $this->auth->id,
                'status'     => 1,
                'createtime' => ['>',time() - 1800],
            ])
            ->find();
        $order && $this->error('你还有待支付订单',$order->id);
        $data['total_price'] = $data['tourists_num'] * $data['goods_price'];
        $data['payment_amount'] = $data['total_price'];
        if ($data['coupon_id']) {
            $coupon = db('coupon')
                ->where([
                    'id' => $data['coupon_id'],
                    'validity_time' => ['<',time()],
                    'status' => 1,
                ])
                ->find();
            !$coupon && $this->error('优惠券无效');
            $data['verifier_id'] = $coupon['user_id'];
            if ($data['total_price'] > $coupon['threshold']) {
                if ($coupon['type'] == 1) {
                    $data['payment_amount'] = $data['total_price'] - $coupon['value'];
                } elseif ($coupon['type'] == 2) {
                    $data['payment_amount'] = $data['total_price'] * $coupon['value'] / 100;
                }
            }
        }
        try {
            $result = $this->model->save($data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if (!$result) {
            $this->error('保存失败');
        }
        $this->success('订单创建成功', $this->model);
    }


    /**
     * 支付
     *
     */
    public function pay()
    {
        $data = [
            'id'             => $this->request->post('id/s'),
            'payment_method' => $this->request->post('payment_method/s'),
        ];
        $rule = [
            'id'             => 'require',
            'payment_method' => 'require|in:1,2',
        ];

        $msg = [
            'payment_method.in' => '支付方式 1微信 2支付宝'
        ];

        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $order = $this->model
            ->with('goods,coupon,user,distributor,verifier')
            ->where([
                'order.id'      => $data['id'],
                'order.user_id' => $this->auth->id,
                'order.status'  => 1,
            ])->find();
        $order['coupon']['status'] == 2  && $this->error('优惠券失效');
        // try {
        //     $result = $this->model->update($data);
        // } catch (\Exception $e) {
        //     $this->error($e->getMessage());
        // }
        // if (!$result) {
        //     $this->error('保存失败');
        // }
        // $this->success('保存成功');
    }


    public function travelDate()
    {
        $start = $this->request->post('start/s', date('Y-m-d', strtotime('monday this week', strtotime(date('Y-m-1')))));
        $end = $this->request->post('end/s', date('Y-m-d', strtotime('sunday this week', strtotime(date('Y-m-t')))));
        dump([$start,$end]);
        if ($start > $end) {
            [$start, $end] = [$end, $start];
        }
        $list = $this->model
            ->field('id,travel_date,return_date')
            ->where([
                'user_id|distributor_id|verifier_id' => $this->auth->id,
                'travel_date'                        => ['<=',$end],
                'return_date'                        => ['>=',$start],
                // 'status'                             => ['in',[2,3,4]],
            ])
            ->order('travel_date asc,id asc')
            ->select();
        $trips = [];
        foreach ($list as $v) {
            $last = strtotime(min($end, $v['return_date']));
            for ($i = strtotime($v['travel_date']); $i <= $last; $i += 86400) {
                $trips[date('Y-m-d',$i)][] = $v;
            }
        }
        $this->success('返回成功',$trips);
    }


}
